import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '../entitys/user.entity';
import { AuthorityService } from './authority.service';

@Injectable()
export class LoginService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly usersRepository: Repository<UserEntity>,
    private readonly authorityService: AuthorityService,
  ) {}

  async loginService(LoginDto) {
    const selectUserSql = `SELECT * FROM t_user WHERE f_user_account='${LoginDto?.fUserAccount}' AND f_user_password='${LoginDto?.fUserPassword}'`;
    const userInfo = await this.usersRepository.query(selectUserSql);
    if (JSON.stringify(userInfo) === '[]') {
      throw new HttpException('用户名或密码错误', 1002);
    }
    const jwtPload = {
      id: userInfo[0].f_id,
      userAccount: userInfo[0].f_user_account,
    };

    const userIfo = {
      id: userInfo[0].f_id,
      name: userInfo[0].f_user_real_name,
    };

    const token = await this.authorityService.getToken(jwtPload);

    let oneMenuSql = `SELECT d.* FROM t_user_role a 
                        INNER JOIN t_role b ON a.f_role_id = b.f_id 
                        INNER JOIN t_role_auth c ON b.f_id = c.f_role_id 
                        INNER JOIN t_author d ON c.f_auth_id = d.f_id WHERE a.f_user_id=? ORDER BY d.f_sort ASC`;

    const twoMenuSql = 'SELECT * FROM t_author WHERE  f_pid = ?';

    let authList = await this.usersRepository.query(
      oneMenuSql,
      userInfo[0].f_id,
    );

    // node循环调用异步方法，实现同步：第一种方式
    // for (let i = 0; i < authList.length; i++) {
    //   let oneMenu = authList[i]
    //   oneMenu["children"] = []
    //   const result = await this.usersRepository.query(twoMenuSql, oneMenu.f_id)
    //   oneMenu.children.push(...result)
    // }

    // node循环调用异步方法，实现同步：第二种方式
    // await Promise.all(authList.map(async (oneMenu) => {
    //   oneMenu["children"] = []
    //   const result = await this.usersRepository.query(twoMenuSql, oneMenu.f_id)
    //   oneMenu.children.push(...result)
    // }));

    // node循环调用异步方法，实现同步：第三种方式
    // for (const oneMenu of authList) {
    //   oneMenu["children"] = []
    //   const result = await this.usersRepository.query(twoMenuSql, oneMenu.f_id)
    //   oneMenu.children.push(...result)
    // }

    // node循环调用异步方法，实现同步：第四种方式
    for (const oneMenu in authList) {
      if (authList[oneMenu].f_pid === '0') {
        authList[oneMenu]['children'] = [];
        authList[oneMenu]['children'] = await this.usersRepository.query(
          twoMenuSql,
          authList[oneMenu].f_id,
        );
      }
    }

    authList = authList.filter((item) => item.f_pid === '0');

    return {
      userIfo,
      token,
      authList,
    };
  }
}
